package kalambury.srv;

import kalambury.db.UserEntity;

import javax.naming.InitialContext;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.KeyStore;
import java.util.Hashtable;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: damienix
 * Date: 02.11.12
 * Time: 22:27
 * To change this template use File | Settings | File Templates.
 */

/**
 * Klasa implementująca główny serwer TCP+SSL
 */
public class ServerImpl  {

    /**
     * socket nasłuchujący serwera
     */
    private static ServerSocket serverSocket;
    /**
     * stan gry
     */
    public static GameState state=new GameState();

    /**
     * wrapper dla aplikacji konsolowej
     * @param args parametry
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {
        run();
    }

    /**
     * inicjalizacja serwera TCP+SSL
     * @throws Exception
     */
    public static void run() throws Exception {
        char[] passphrase = "changeit".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS");
        InputStream in = ServerImpl.class.getResourceAsStream("/keystore");
        ks.load(in, passphrase);
        KeyManagerFactory tms = KeyManagerFactory.getInstance("SunX509");
        tms.init(ks,passphrase);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(tms.getKeyManagers(), null, null);

        SSLServerSocketFactory sf = sslContext.getServerSocketFactory();
        serverSocket = sf.createServerSocket(1337);
        System.out.println("Server ok @ 1337");

        while (true)
        {
            Socket client=serverSocket.accept();
            new Thread(new ClientThread(client)).start();
        }
    }

}
